require('./db/initdb');
const { mongoUrl, TOKEN_SECRET_KEY, uploadPath, publicPath } = require('./serverOpt');
const createError = require('http-errors');
const express = require('express'); //ws相关
const expressWs = require('express-ws');
const logger = require('morgan');
const cors = require('cors')
const app = express();
expressWs(app); //ws相关

app.use(express.static(publicPath));
const session = require('express-session');
const MongoStore = require('connect-mongo');

app.use(cors());
// 配置中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(
	session({
		resave: true, //resave是指每次请求都重新设置session cookie，假设你的cookie是10分钟过期，每次请求都会再设置10分钟
		secret: 'jinZhu',
		saveUninitialized: false, //saveUninitialized是指无论有没有session cookie，每次请求都设置个session cookie ，默认给个标示为 connect.sid
		// cookie: { expires: false },//这里确保了session cookie在浏览器关闭时会过期
		store: new MongoStore({
			mongoUrl: mongoUrl,
			ttl: 7 * 24 * 60 * 60,
			// ttl: 10 * 60
		}),
	}),
);

// 配置路由
const wsRouter = require('./routes/backend/ws');
const groupRouter = require('./routes/backend/group');
const deviceRouter = require('./routes/backend/device');
const indexRouter = require('./routes/index');
const backendUser = require('./routes/backend/user');
const anchorRouter = require('./routes/backend/anchor');
const uploadRouter = require('./routes/collect/upload');
//用户登录相关
app.use('/wsRouter', wsRouter);
app.use('/', indexRouter);

// 添加后台API的登录检查中间件
app.use('/api/backend/', (req, res, next) => {
	// console.log(req.session);
	if (!req.session.userId) {
		return res.status(401).json({
			code: -1,
			msg: '用户未登录',
		});
	}
	next();
});

// 后端管理平台相关 /api/backend
app.use('/api/backend/user', backendUser);
app.use('/api/backend/group', groupRouter)
app.use('/api/backend/device', deviceRouter)
app.use('/api/backend/anchor', anchorRouter)

// 数据采集端相关 /api/collect
app.use('/api/collect/upload', uploadRouter)

// 错误处理
app.use(function (err, req, res, next) {
	const errMsg = err.message;
	if (errMsg == '未找到页面或内容') {
		console.error(`${errMsg}:${req.url}`);
	} else {
		console.error(`node未处理的错误:${req.url}`, err);
	}
	res.status(err.status || 500).json({
		code: err.status || 500,
		msg: errMsg,
	});
});

// 捕捉 404 错误，并转发到错误处理器
app.use(function (req, res, next) {
	next(createError(404, '未找到页面或内容'));
});

module.exports = app;
